package com.zcccccy.rocketmq.consumer.listener;

import cn.hutool.core.date.DateUtil;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.consumer.MessageListener;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 消息监听
 * 
 * @projectName: zcccccy
 * @packageName: com.zcccccy.extend.rocketmq.consumer.listener
 * @author: zcy
 * @createTime: 2024/1/27
 * @productName: For Mac IntelliJ IDEA
 */
@Component
public class RocketMQListener implements MessageListener {

    private static final Logger log = LoggerFactory.getLogger(RocketMQListener.class);

    /**
     * 消息消费 返回success表示消费成功
     * 
     * @param messageView
     * @return org.apache.rocketmq.client.apis.consumer.ConsumeResult
     * @author zcy
     * @createTime 2024/1/28 11:00
     **/
    @Override
    public ConsumeResult consume(MessageView messageView) {

        log.info("接收时间：{}", DateUtil.date());

        log.info("消费消息：{}", messageView);

        // 指定字符集（Charset）
        Charset charset = StandardCharsets.UTF_8;
        // 将ByteBuffer转换为String
        String result = charset.decode(messageView.getBody()).toString();
        log.info("消费消息内容：{}", result);


        // TODO 处理业务

        // 可以通过不同主题做不同处理
        // String topic = messageView.getTopic();

        if (messageView.getDeliveryAttempt() == 3){
            // 重试到最大重试次数可实现其他补救措施
        }

        // 如果业务处理失败则返回失败
        //return ConsumeResult.FAILURE;

        // 消费成功返回成功
        return ConsumeResult.SUCCESS;
    }
}
